package com.algrithom.find;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 寻找最接近当前值的元素 注：如果是数组中有重复的数据，则不能使用二分查找的方式
 *
 * @author think
 * @version 1.0.0
 * @since 2019/12/22
 */
public class FindLatested {
    
    public static void main(String[] args){
        //    int[] array = {1, 7, 7, 9, 0, 4, 7,8,9,7,10,7,111,7};
        int[] array = {1,7,9,0,4,8,9,10,111};
        int key = 6;
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.binarySearch(array,key));
        System.out.println(findLatestedEle(array,key).stream().map(String::valueOf).collect(Collectors.joining(",")));
    }
    
    private static List<Integer> findLatestedEle(int[] array,int key){
        int low = 0;
        int high = array.length - 1;
        int mid;
        int minLen = Integer.MAX_VALUE;
        int minIndex = 0;
        int len;
        List<Integer> result = new ArrayList<>();
        while (low <= high) {
            String temp = String.valueOf(Math.ceil(Math.addExact(low,high) / 2));
            mid = Integer.parseInt(temp.substring(0,temp.indexOf(".")));
            if (key > array[mid]) {
                low = mid + 1;
                len = key - array[mid];
            } else if (key < array[mid]) {
                high = mid - 1;
                len = array[mid] - key;
            } else {
                minIndex = mid;
                result.add(minIndex);
                break;
            }
            if (len < minLen) {
                result.clear();
                minLen = len;
                minIndex = mid;
                result.add(minIndex);
            } else if (minLen == len) {
                minIndex = mid;
                result.add(minIndex);
            }
        }
        return result;
    }
}
